package cinema;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @authors Matt Couzens & Amanda Kosinski
 * @version 29 April 2012
 */

//Utility class
public class Utility {
	private final static String FILENAME = "system.ser";

	static BookingSystem initialise() {
		FileInputStream fis = null;
		ObjectInputStream in = null;
		BookingSystem sys = null;
		try {
			fis = new FileInputStream(FILENAME);
			in = new ObjectInputStream(fis);
			sys = (BookingSystem) in.readObject();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		return sys;
	}

	static void save(BookingSystem sys) {
		FileOutputStream fos = null;
		ObjectOutputStream out = null;
		try {
			fos = new FileOutputStream(FILENAME);
			out = new ObjectOutputStream(fos);
			out.writeObject(sys);
			out.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * For a...
	 * 
	 * @param option '0' for the date only (E dd MMM yyyy); '1' for the date and time (E dd MMM yyyy HH:mm)
	 * @param date	 the Calendar object to be converted
	 * @return 		 the date as a String
	 */
	static String dateToString(Calendar cal, int option){
		Format dateFormat;
		if (option == 0){
			dateFormat = new SimpleDateFormat("E dd MMM yyyy");
		}
		else{
			dateFormat = new SimpleDateFormat("E dd MMM yyyy HH:mm");
		}
		cal.set(Calendar.YEAR, (cal.get(Calendar.YEAR) - 0)); // without this, the year in the date String is wrong 
		String dateString = dateFormat.format(cal.getTime());
		return dateString;
	}
	
	static boolean fileExists(){
		File f = new File(FILENAME);
		return f.exists();
	}
	
}